package com.jdk.demo.nio.mReactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MthreadHandler implements Runnable {

	final SocketChannel channel;
    final SelectionKey sk;
    ByteBuffer input = ByteBuffer.allocate(1024);
    ByteBuffer output = ByteBuffer.allocate(1024);
    static final int READING = 0, SENDING = 1;
    int state = READING;

    ExecutorService pool = Executors.newFixedThreadPool(2);
    static final int PROCESSING = 3;

    public MthreadHandler(Selector selector, SocketChannel c) throws IOException {
        channel = c;
        c.configureBlocking(false);
        // Optionally try first read now
        sk = channel.register(selector, 0);

        //将Handler作为callback对象
        sk.attach(this);

        //第二步,注册Read就绪事件
        sk.interestOps(SelectionKey.OP_READ);
        selector.wakeup();
    }

    void process() {
    	try {
			channel.read(input);
		} catch (IOException e) {
			e.printStackTrace();
		}
        input.flip();
        byte[] b = new byte[input.remaining()];
        input.get(b);
        System.out.println(new String(b));
    }

    @Override
	public void run() {
        try {
            if (state == READING) {
                read();
            } else if (state == SENDING) {
                send();
            }
        } catch (IOException ex)
        { /* ... */ }
    }


    synchronized void read() throws IOException {
    	System.out.println("read in: " + Thread.currentThread().getName());
    	//任务异步处理
    	pool.submit(() -> process());

        //下一步处理写事件
        sk.interestOps(SelectionKey.OP_WRITE);
        this.state = SENDING;
  }

    void send() throws IOException {
      	//任务异步处理
    	pool.submit(() -> process2());
    }

	void process2() {
		output.put("server hello".getBytes());
    	output.flip();
    	try {
			channel.write(output);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}
